<?php
namespace Admin\Controller;
use Think\Controller;
//足球世界杯
class WordCupController extends CommonController {

    const AppID     =   'wxb2dfa5282782f280';
    const AppSecret =   'a814e9599f2da97118888ebcb447d3f8';

    public function send(){


        if (IS_AJAX)
        {
            $tem      = I('post.tem','','htmlspecialchars');
            $keyword1 = I('post.keyword1','','htmlspecialchars');
            $keyword2 = I('post.keyword2','','htmlspecialchars');
            $keyword3 = I('post.keyword3','','htmlspecialchars');
            $keyword4 = I('post.keyword4','','htmlspecialchars');
            $keyword5 = I('post.keyword5','','htmlspecialchars');
            $touser   = I('post.touser','','htmlspecialchars');
            $uid      = I('post.uid','','int');
            $emphasis_keyword   =   I('post.emphasis_keyword','','htmlspecialchars');
            $template_data      =   array();

            $appid      =   self::AppID;
            $secret     =   self::AppSecret;
            $game       =   'worldcup';

            if ($uid)
            {
                $template_data = M('worldcup_template_send_copy')->where(array('uid'=>$uid))->order('wxopen_template_send_id desc')->limit(1)->select();
            }
            else
            {
                $template_data  =   M('worldcup_template_send_copy')->group('touser')->order('wxopen_template_send_id desc')->select();
            }

            //模板消息
            $msgssage   =   array();
            if ($keyword1){
                $msgssage['keyword1'] = array(
                    'value'=>$keyword1,
                    'color'=>'#173177',
                );
            }

            if ($keyword2){
                $msgssage['keyword2'] = array(
                    'value'=>$keyword2,
                    'color'=>'#173177',
                );
            }

            if ($keyword3){
                $msgssage['keyword3'] = array(
                    'value'=>$keyword3,
                    'color'=>'#173177',
                );
            }

            if ($keyword4){
                $msgssage['keyword4'] = array(
                    'value'=>$keyword4,
                    'color'=>'#173177',
                );
            }

            if ($keyword5){
                $msgssage['keyword5'] = array(
                    'value'=>$keyword5,
                    'color'=>'#173177',
                );
            }

            //数据拼装
            $redis = new \Redis();
            $redis->connect('127.0.0.1',6379);
            $access_token = $this->redis_access_token($appid,$secret,$redis);

            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";

            if(empty($tem))
            {
                $tem = "JYhnftZ3mQ1OBdQ9a2EjTYAQomZt-gnVOJbLRWj4WYM";
            }

            //保存已经发过的用户
            $worldcup_member        =   $redis->get($game.'_member');
            if (! empty($worldcup_member))
            {
                $worldcup_member        =   json_decode($worldcup_member,true);
            }
            else
            {
                $worldcup_member    =   array();
            }

            //记录加入对的的数量
            $list_nums              =   0;

            //链接swoolw服务器
            $client = new \swoole_client(SWOOLE_SOCK_TCP);
            //连接到服务器
            if (!$client->connect('127.0.0.1', 9501, 0.5))
            {
                $msg['state']   =   -1;
                $msg['error']   =   'swoole服务器连接失败';
                $this->ajaxReturn ($msg,'JSON');
            }

            foreach($template_data as $key=> $value)
            {
                if (! in_array($value['touser'], $worldcup_member) && $value['form_id'] !=  'the formId is a mock one' )
                {
                    $data = array(
                        'touser'=>$value['touser'],
                        'template_id'=>$tem,
                        'page'=>'pages/index/index',
                        'form_id'=>$value['form_id'],
                        'data'=>$msgssage,
                        'emphasis_keyword'=>'keyword2.DATA'
                    );

                    //推送数据写入redis队列
                    $post_data 			=	array();
                    $post_data['data']	=	$data;
                    $post_data['url']	=	$url;
                    $post_data['id']	=	$value['wxopen_template_send_id'];
                    $redis->rPush('push_'.$game,json_encode($post_data));

                    //用户追加到推送约束list里去
                    $worldcup_member[]  =   $value['touser'];
                    $member_data    =   json_encode($worldcup_member);
                    $redis->set($game.'_member', $member_data);

                    $list_nums++;
                }
            }


            if (!empty($list_nums))
            {
                //向swoole服务端发送推送请求
                $data			    =	array();
                $data['game']	    =	$game;  //'worldcup';
                $data['action']     =	'Push';
                $data['test']       =   true;
                $data['call_back']  =   'http://test.beikg.cn/home/SwooleClient/api_accept';    //返回跟更新或删除数据的接口 http://test.beikg.cn/home/index/api_accept
                $msg 			    =	serialize($data);

                $return_msg         =   array();
                //向服务器发送数据
                if (!$client->send($msg))
                {
                    $return_msg['state']   =   -1;
                    $return_msg['error']   =   '发送到swoole失败';
                }
                else
                {
                    $return_msg['state']   =   200;
                    $return_msg['error']   =   '发送swoole成功';
                }
                $client->close();
                //关闭连接
                $this->ajaxReturn ( $return_msg,'JSON');

            }
            else
            {
                $msg['state']   =   -1;
                $msg['error']   =   '发送失败';
                $this->ajaxReturn ($msg,'JSON');
            }
        }

        $this->display('send');
    }

    public function send_status()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);

        $game           =   'worldcup';
        $game_message   =	'push_'.$game;
        $message 	    =	'update_'.$game;    //已经发送的
        $success_message=	'successed_'.$game;

        $worldcup_member        =   $redis->get($game.'_member');
        $worldcup_member        =   json_decode($worldcup_member,true);

        $redis->set($game.'_member','');

        print_r($worldcup_member);

        $loop 	=	true;
        while ($loop)
        {
            $value = $redis->lpop($game_message);

            if(! empty($value))
            {
                //投递异步任务
                print_r($value);

            }
            else
            {
                $loop	=	false;
            }
        }

        $loop_success 	=	true;
        while ($loop_success)
        {
            $value = $redis->lpop($success_message);

            if(! empty($value))
            {
                //投递异步任务
                echo "id=".$value."</br>";
            }
            else
            {
                $loop_success	=	false;
            }
        }

        $loop_ed 	=	true;
        while ($loop_ed )
        {
            $valued = $redis->lpop($message);

            if(! empty($valued))
            {
                //投递异步任务
                echo "id=".$valued."</br>";
            }
            else
            {
                $loop_ed	=	false;
            }
        }

    }

    public function clean()
    {

    }
}